//岛屿数量
//测试链接：https://leetcode.cn/problems/number-of-islands/
public class NumIslands {
    int[] dx = {-1, 1, 0, 0};
    int[] dy = {0, 0, -1, 1};
    int n, m;
    boolean[][] vis;
    int ans;
    public int numIslands(char[][] grid) {
        n = grid.length; m = grid[0].length; ans = 0;
        vis = new boolean[n][m];

        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(!vis[i][j] && grid[i][j] == '1' ) {
                    dfs(grid,i,j);
                    vis[i][j] = true;
                    ans++;
                }
            }
        }

        return ans;
    }

    public void dfs(char[][] grid, int i, int j) {

        for(int k = 0; k < 4 ;k++) {
            int x = dx[k] + i;
            int y = dy[k] + j;
            if(x >= 0 && x < n && y >= 0 && y < m && !vis[x][y] && grid[x][y] == '1') {
                vis[x][y] = true;
                dfs(grid, x, y);
            }
        }
    }
}
